//定义用于显示测试执行记录的外层grid
var testRunLogGrid = Ext.create('Ext.grid.Panel', {
    alias: 'widget.MainGrid',
    header: false,
    height: '60%',
    border: false,
    store: testRunlogStore,
    dockedItems: [{
        dock: 'top',
        xtype: 'toolbar',
        items: [{
            text: '添加',
            tooltip: '添加执行记录',
            itemId: 'testRunAddLogButton',
            icon: 'static/images/icons/fam/add.gif',
            listeners: {
                click: function () {
                    var nowData = testRunlogStore.getData();
                    var flag = false;
                    Ext.each(nowData.items, function (record) {
                        if (record.data.isCreate == 1) {
                            Ext.Msg.alert("错误", "请先将当前创建执行记录保存！");
                            flag = true;
                        }
                    });
                    if (!flag) {//如果当前存在未保存的新建执行纪律则不能添加新的执行记录
                        var testDesign = testRunDetailForm.down('#testRunDetailFormTestDesign').testDesign;
                        if (testDesign == '')
                            Ext.Msg.alert("错误", "请先选择执行的测试计划！");
                        else {
                            Ext.Ajax.request({//获取所执行的测试计划的测试步骤
                                url: zuulUrl + '/' + testServiceName + '/common/testDesign/step/' + testDesign,
                                async: false, // ASYNC 是否异步( TRUE 异步 , FALSE 同步)
                                success: function (response, opts) {
                                    var obj = Ext.decode(response.responseText);
                                    var logId = Ext.create("MyApp.data.MyModelX").data.id.replace(/-/g, "");
                                    Ext.each(obj, function (data) {
                                        data.testRunLog = logId;
                                        data.isPass = -1;//因为是新添加的测试执行记录,所以他旗下的测试步骤的isPsss都是未完成
                                    });
                                    for (i = 0, len = obj.length; i < len; i++) {//将获得的测试步骤作为新添加的执行记录的执行步骤添加到储存步骤的数组中
                                        obj[i].reason = ' ';//反之reason那一栏是null
                                        outSideSteps.push(obj[i]);
                                    }
                                    var newRecord = {
                                        "id": logId,
                                        "host": "",
                                        "status": -1,//-1表示这个执行记录未完成
                                        "duration": "",
                                        "browserVersion": "",
                                        "os": "",
                                        "isCreate": 1//表示这个执行记录是新添加的
                                    };
                                    var logArr = new Array();
                                    logArr.push(newRecord);
                                    Ext.each(testRunlogStore.getData().items, function (log) {
                                        logArr.push(log.data);
                                    });
                                    testRunlogStore.setData(logArr);//不知为何从审核界面转到执行界面是用insert添加执行记录会堆栈溢出
                                    //testRunlogStore.insert(0,newRecord);
                                },
                                failure: function (response, opts) {
                                    var obj = Ext.decode(response.responseText);
                                    if (obj.code == 401 || obj.code == 402 || obj.code == 403)
                                        Ext.Msg.alert("错误", obj.message);
                                    else
                                        Ext.Msg.alert("错误", "该功能暂时不可用！");
                                }
                            });
                        }
                    }
                }
            }
        }, '-', {
            text: '删除',
            tooltip: '删除执行记录',
            itemId: 'testRunDeleteLogButton',
            icon: 'static/images/icons/fam/delete.gif',
            listeners: {
                click: function () {
                    var item = testRunLogGrid.getSelectionModel().getSelected();// 得到被选择的行的数组.
                    if (item.length == 0)
                        Ext.Msg.alert('错误', '请选择要删除的执行记录！');
                    else {
                        Ext.MessageBox.confirm('删除', '你确定要将该执行记录删除吗', function (btn) {
                            if (btn === 'yes') {
                                var record = testRunlogStore.getById(item.items[0].data.id);
                                for (var i = 0; i < outSideSteps.length; i++) {//要将储存执行步骤的数组中的步骤删除掉
                                    if (record.data.id == outSideSteps[i].testRunLog)
                                        outSideSteps.splice(i--, 1);
                                }
                                testRunlogStore.remove(record);
                                testRunLogStepStore.removeAll();//将下方显示测试步骤详情的grid也清空
                            }
                        });
                    }
                }
            }
        }]
    }],
    columns: [new Ext.grid.RowNumberer(), {
        text: "测试机",
        dataIndex: 'host',
		align: 'center',
        sortable: false,
        editor: {
            completeOnEnter: true,//是否允许用回车结束输入
            field: {
                xtype: 'textfield',
                allowBlank: false//是否允许为空
            }
        }
    }, {
        text: "状态",
		align: 'center',
        dataIndex: 'status',
        sortable: false,
        renderer: function (value) {
            if (value == -1)
                return "<img src='static/images/icons/fam/warning.ico' style='vertical-align:text-top;'  />未完成";
            else if (value == 0)
                return "<img src='static/images/icons/fam/cross.gif' style='vertical-align:text-top;'  /> 失败";
            else
                return "<img src='static/images/icons/fam/accept.png' style='vertical-align:text-top;'  />成功";
        },
    }, {
        text: "执行时长[分钟]",
        sortable: false,
		align: 'center',
        width: 150,
        dataIndex: 'duration',
        editor: {
            completeOnEnter: true,//是否允许用回车结束输入
            field: {
                xtype: 'numberfield',
                minValue: 0,//不允许输入负数（取代allowNegative）
                allowBlank: false//是否允许为空
            }
        }
    }, {
        text: "浏览器版本",
		align: 'center',
        sortable: false,
        dataIndex: 'browserVersion',
        editor: {
            completeOnEnter: true,//是否允许用回车结束输入
            field: {
                xtype: 'textfield',
                allowBlank: false//是否允许为空
            }
        }
    }, {
        text: "操作系统",
		align: 'center',
        sortable: false,
        dataIndex: 'os',
        editor: {
            completeOnEnter: true,//是否允许用回车结束输入
            field: {
                xtype: 'textfield',
                allowBlank: false//是否允许为空
            }
        }
    }, {
        text: "创建时间",
        sortable: false,
		align: 'center',
        dataIndex: 'createDate',
        flex: 1,
        renderer: function (value) {
            if (value == null)
                return '无';
            else
                return value.replace('T', '  ');
        }
    }],
    // autoWidth: true,
    selModel: {
        selType: 'cellmodel'
    },
    // autoHeight: true,
    plugins: [{
        ptype: 'rowexpander',
        expandOnDblClick: false,//是否允许双击行然后展开
        rowBodyTpl: ['<div id="z{id}">', '</div>']
    }, {
        ptype: 'cellediting',
        clicksToEdit: 1,
        listeners: [{
            beforeedit: function (edit, e) {
                return testRunCreateOrUpdate == 0 || testRunTabPanel.canUpdate;// 如果是新建操作或者允许编辑的话
            }
        }, {
            edit: function (editor, context, eOpts) {
                destroyInnerGrid(context.record, false);//先将rowBody清空
                displayInnerGrid(context.record, 'InnerGrid');//再加载rowBody
            }
        }]
    }],
    collapsible: true,
    animCollapse: false,
    iconCls: 'icon-grid',
    listeners: [{
        itemclick: function (view, record, item, index, e, eOpts) {//当选择对应的执行记录时，下面的测试步骤详情也要随之改变
            testRunLogStepStore.removeAll();
            var steps = new Array();
            Ext.each(outSideSteps, function (step) {
                if (step.testRunLog == record.data.id)
                    steps.push(step);
            });
            testRunLogStepStore.setData(testDesignBorderShot(steps));
        }
    }]
});

//添加展开监听事件
testRunLogGrid.getView().on('expandBody', function (rowNode, record, expandRow, eOpts) {
    destroyInnerGrid(record, false);//先将rowBody清空
    displayInnerGrid(record, 'InnerGrid');//再加载rowBody
});

Ext.define('InnerGrid', {
    extend: 'Ext.grid.Panel',
    header: false,
    selModel: {
        selType: 'cellmodel'
    },
    columns: [new Ext.grid.RowNumberer(),
        {
            text: "步骤名称",
            dataIndex: 'name',
            flex: 0.5,
            sortable: false,
        }, {
            text: "状态",
            dataIndex: 'isPass',
            sortable: false,
            renderer: function (value) {
                if (value == -1)
                    return "<img src='static/images/icons/fam/warning.ico' style='vertical-align:text-top;'  />未完成";
                else if (value == 0)
                    return "<img src='static/images/icons/fam/cross.gif' style='vertical-align:text-top;'  /> 失败";
                else
                    return "<img src='static/images/icons/fam/accept.png' style='vertical-align:text-top;'  />成功";
            },
            editor: {
                field: {
                    xtype: 'combo',
                    editable: false,//防止用户直接在下拉框里输入
                    emptyText: '执行结果',
                    store: testRunStepStatusStore,
                    queryMode: 'local',
                    displayField: 'statusValue',
                    valueField: 'statusNum',
                    allowBlank: false//是否允许为空
                }
            }
        },
        {
            text: "理由",
            dataIndex: 'reason',
            flex: 1,
            sortable: false,
            renderer: function (v, m, r) {
                if (v == null)//不知道为什么如果显示的是null就无法触发点击事件
                    return '';
                else if (v.length < 15)
                    return v;
                else
                    return '内容过长,请展开查看';
            },
            listeners: [{
                click: function (a, b, c, d, e, f) {
                    if (testRunCreateOrUpdate == 0 || testRunTabPanel.canUpdate) {//如果允许编辑的话
                        testRunStepEditorWin.show();
                        window.addEventListener('message', testRunPutEditDataIntoGrid, false);//添加监听
                        testRunListenFlag = true;//标志现在是添加监听而触发的这个函数
                        testRunListenRowData = f;//将点击的执行步骤的行数据储存起来
                        testRunStepReasonEditorIFrame.getFrame().contentWindow.postMessage({
                            status: 5,
                            text: f.data.reason
                        }, zuulUrl + '/' + webServiceName + '/editor');//将点击的执行步骤的结果理由显示到编辑器上
                    }
                }
            }]
        }
    ],
//	columnLines: true,
//	autoWidth: true,
//	autoHeight: true,
    // width: 400,renderId
    // height: 200,
    iconCls: 'icon-grid',
    plugins: {
        cellediting: {
            clicksToEdit: 1,
            listeners: [{
                beforeedit: function () {
                    return testRunCreateOrUpdate == 0 || testRunTabPanel.canUpdate;//如果是新建操作或者允许编辑的话
                }
            }, {
                edit: function (editor, context, eOpts) {
                    //当编辑了步骤结果之后要把数据同步到储存执行步骤的数组
                    var data = context.record.data, isFinish = true, isPass = true;
                    for (var i = 0, len = outSideSteps.length; i < len; i++) {
                        if (outSideSteps[i].id == data.id) {
                            outSideSteps[i].isPass = data.isPass;
                            break;
                        }
                    }
                    //修改了某个执行步骤的结果之后就要遍历该执行记录下的所有步骤查看是否会影响到整体状态
                    for (var i = 0, len = outSideSteps.length; i < len; i++) {
                        if (outSideSteps[i].testRunLog == data.testRunLog) {
                            if (outSideSteps[i].isPass == -1)
                                isFinish = false;
                            else if (outSideSteps[i].isPass == 0)
                                isPass = false;
                        }
                    }
                    var result;
                    if (!isFinish)//有一个未完成，整体状态就是未完成
                        result = -1;
                    else
                        result = isPass ? 1 : 0;//没有一个未完成但是有一个失败整体就是失败
                    var record = testRunlogStore.getById(data.testRunLog);
                    if (record.get('status') != result) {//值会改变才去修改
                        record.set('status', result);//将整体结果赋值到外层grid
                        destroyInnerGrid(record, false);//先将rowBody清空
                        displayInnerGrid(record, 'InnerGrid');//再加载rowBody
                    }
                }
            }]
        },
        rowexpander: {
            rowBodyTpl: new Ext.XTemplate(
                '{reason}'
            )
        }
    }
    // constructor: function () {
    //     this.callParent(arguments); // 调用父类的构造函数,不然会报错
    //     this.getEl().swallowEvent([
    //             						'mousedown', 'mouseup', 'click',
    //             						'contextmenu', 'mouseover', 'mouseout',
    //             						'dblclick', 'mousemove'
    //             					]);
    // }
});

// 用于显示测试执行的测试步骤的详细信息grid
var testRunLogStepGrid = Ext.create('Ext.grid.Panel', {
    store: testRunLogStepStore,
//    collapsible: true, // 有没有按钮向内缩进
//    collapseDirection:'left',
//    titleAlign:'right',
//    headerPosition:'right',
    autoScroll: true, //大小溢出时自动出现滚动条
    height: '40%',
    header: {
        height: 23,
        padding: '2 0 2 10 '
    },
    title: '测试步骤信息',
    border: false,
    columns: [new Ext.grid.RowNumberer(),// 显示行号
        {
            text: '名称',
            width: 100,
            dataIndex: 'name',
            sortable: false
        }, {
            text: '内容',
            dataIndex: 'description',
            flex: 1,
            sortable: false,
            renderer: function (v, m, r) {
                if (v.length < 15)
                    return v;
                else
                    return '内容过长,请展开查看';
            }
        }, {
            text: '期望结果',
            dataIndex: 'expectedResult',
            flex: 0.5,
            sortable: false
        }],
    plugins: {
        rowexpander: {
            rowBodyTpl: new Ext.XTemplate(
                '{description}'
            )
        }
    }
});

//用于显示测试执行的审核记录
var testRunCheckLogGrid = Ext.create('Ext.grid.Panel', {
    store: testRunCheckLogStore,
    border: false,
    columns: [new Ext.grid.RowNumberer(),//显示行号
        {
            text: '状态',
            width: 100,
            renderer: function (v, record) {
                if (record.record.data.isFinish == 1) {
                    if (record.record.data.isPass == 1)
                        return '审核通过';
                    else
                        return '审核不通过';
                } else
                    return '审核中';
            },
        }, {
            text: '审核人',
            dataIndex: 'checkMan',
            flex: 0.5
        }, {
            text: '审核日期',
            dataIndex: 'checkDate',
            flex: 0.5,
            renderer: function (value) {
                return value.replace('T', '  ');
            }
        }, {
            text: '查看批注',
            align: 'center',
            sortable: false,
            xtype: 'actioncolumn',
            width: 100,
            items: [{
                icon: 'static/images/icons/fam/look.ico',
                tooltip: '查看批注',
                handler: function (grid, rowIndex, colIndex) {
                    var id = testRunCheckLogStore.getAt(rowIndex).data.id;
                    Ext.Ajax.request({//然后去后台请求该审核记录的批注内容
                        url: zuulUrl + '/' + testServiceName + '/testRunCheck/common/annotate/' + id,
                        async: true,   //ASYNC 是否异步( TRUE 异步 , FALSE 同步)
                        success: function (response, opts) {
                            var data = response.responseText;
                            testRunCheckLogAnnotatoWin.show();
                            testRunCheckLogAnnotatoWin.down('#testRunCheckLogAnnotatoPanel').setHtml('<p><b>' + data + '</b></p>');
                        },
                        failure: function (response, opts) {
                            Ext.Msg.alert('失败', '该操作暂时不可用！');
                        }
                    });
                }
            }]
        }]
});